<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">



        <el-button type="primary" @click="showDialog">

          <el-icon>
            <Plus />
          </el-icon>
          &nbsp;
          添加</el-button>
      </div>

    </template>
    <!-- label就是你该列的名字 -->
    <!-- data你所渲染数据的数据源 -->
    <!-- props你当前的列的所显示数据对应的属性 -->
    <el-table :data="trademarkList" border style="width: 100%;margin-bottom: 30px;">
      <el-table-column type="index" align="center" label="序号" width="100" />
      <el-table-column prop="tmName" align="center" label="品牌名称" width="180" />
      <el-table-column align="center" label="品牌LoGo">

        <template v-slot="{ row }">
          <div>
            <img :src="row.logoUrl" width="100">
          </div>
        </template>

      </el-table-column>
      <el-table-column prop="address" align="center" label="操作">
        <!-- 列的插槽 -->
        <template v-slot="{ row }">

          <el-button type="warning" :icon="Edit" size="small" @click="uodateTrademarkData(row)"></el-button>
          <el-button type="danger" :icon="Delete" @click="deleteTrademark(row)" size="small"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->

    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 7, 8, 10, 15]"
      :small="small" :disabled="disabled" :background="background" layout="prev, pager, next, jumper,->,sizes, total, "
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <!-- 添加对话框 -->

    <el-dialog v-model="dialogFormVisible" :title="`${Trademark.id ? '编辑品牌' : '添加品牌'}`">
      <el-form :model="Trademark" ref="ruleFormRef" :rules="rules">
        <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName">
          <el-input v-model="Trademark.tmName" autocomplete="off"  />
        </el-form-item>
        <el-form-item label="品牌Logo" :label-width="formLabelWidth" prop="logoUrl">
          <el-upload class="avatar-uploader" :action="`${BASE_URL}/admin/product/upload`" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="Trademark.logoUrl" :src="Trademark.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>


  </el-card>

</template>

<script lang="ts">


export default {
  name: 'Trademark'
}
</script>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'

import type { UploadProps } from 'element-plus'


import { ref, onMounted, reactive } from 'vue'
import { reqGetTrademarkInfoData, reqSaveTrademarkInfoData, reqDeleTrademarkInfo, reqUpdateTrademarkInfo } from "@/api/product/trademark"
import {
  Edit,
  Delete,
  Plus
} from '@element-plus/icons-vue'
// 导入我的数据类型
import type { TrademarkModel, TrademarkListModel, } from '@/api/product/model/TrademarkModel'
//校验开始了
import type { FormInstance, FormRules } from 'element-plus'
const ruleFormRef = ref<FormInstance>()

const currentPage = ref(1)
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '请输入正确格式的品牌名称', trigger: 'blur' },
    { min: 2, max: 6, message: '长度至少在2到6直接', trigger: 'blur' },
  ],
  logoUrl: [
    {
      required: true,
      message: '请插入图片',
      trigger: 'change',
    },
  ]
})

const pageSize = ref(3)

const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const total = ref(0)
//5对话框的数据
const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
// 上传图片的数据
const imageUrl = ref('')
//8
const BASE_URL = import.meta.env.VITE_API_URL
//用于存储我页面的数据
const trademarkList = ref<TrademarkListModel>([])
//初始化我的存储的数据
const initTrademark = () => ({
  tmName: '',
  logoUrl: '',
})
const Trademark = reactive<TrademarkModel>(initTrademark())

//1获取trademark数据的函数
const getTrademarkListData = async () => {
  const res = await reqGetTrademarkInfoData(currentPage.value, pageSize.value)
  // console.log(res)
  // 将请求回来的数据存储到trademarklist身上
  trademarkList.value = res.records
  total.value = res.total
}
//2页面以挂载就请求数据
onMounted(() => {
  getTrademarkListData()
})
// 3页面的数据量
const handleSizeChange = (val: number) => {
  // console.log(`${val} items per page`)
  pageSize.value = val
  currentPage.value = 1
  // 重新请求数据
  getTrademarkListData()
  ElMessage.success('数据请求成功')
}
// 4改变当前的页码
const handleCurrentChange = (val: number) => {
  // 
  // console.log(`current page: ${val}`)
  currentPage.value = val;
  // 重新发送
  getTrademarkListData()
  // 
  ElMessage.success('页面更新完成')


}
// 6点击添加需要展示对话款GV
const showDialog = () => {
  // 展示对话框
  dialogFormVisible.value = true
  //清除上一次残留的数据
  Object.assign(Trademark, initTrademark());
  //因为我的不需要id添加时
  delete Trademark.id
}
//7成功上传之后所触发的函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile



) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  // 将服务器返回的服务器的连接存储到我的trademark 上
  Trademark.logoUrl = response.data
  // 提示成G功
  ElMessage.success('数据添加')
}
//8成功上传之前触发的函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 定义的我的类型数据
  const imageUrlType = ['image/jpeg', 'image/jpg', 'image/gif'];
  if (!imageUrlType.includes(rawFile.type)) {
    // if (rawFile.type) {
    ElMessage.error(' 请上传图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('请输入正确大小的格式的图片')
    return false
  }
  return true
}
//9点击确定触发函数
const AddTrademark = async () => {
  if (Trademark.id) {
    //编辑数据
    await reqUpdateTrademarkInfo(Trademark)


  } else {
    //要调用我成功添加的接口函数
    const res = await reqSaveTrademarkInfoData(Trademark)
    // 当前的页面为1
    currentPage.value = 1
  }


  //重新发送请求
  getTrademarkListData()

  //关闭对话框
  dialogFormVisible.value = false;
  ElMessage.success('操作成功');

}
//10定义一个删除数据的方法
const deleteTrademark = async (row: TrademarkModel) => {
  // 首先要弹出弹窗，给用户以考虑的时间
  ElMessageBox.confirm(
    `你确定要删除${row.tmName}码`,
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })

  //发送请求删除
  const res = await reqDeleTrademarkInfo(row.id as number)

  // 重新发送请求吧
  getTrademarkListData()
}
//11定义一个编辑数据的方法,品牌数据的回显
const uodateTrademarkData = (row: TrademarkModel) => {
  //通过object.assign的方法将我的row重新回显到数据上，这样也可以 不用丢失响应式
  Object.assign(Trademark, row)
  //将弹窗展开
  dialogFormVisible.value = true;



}
// 11校验的方法
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log('submit!')
      AddTrademark()
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
